package com.sctvcloud.qingchuan.ui.activities;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.jiongbull.jlog.JLog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.ui.widget.CustomLinearLayout;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.qingchuan.R;
import com.sctvcloud.qingchuan.application.Cache;
import com.sctvcloud.qingchuan.application.Constances;
import com.sctvcloud.qingchuan.base.BaseActivity;
import com.sctvcloud.qingchuan.beans.DeclareVo;
import com.sctvcloud.qingchuan.beans.DoUpEvent;
import com.sctvcloud.qingchuan.beans.DeclareBean;
import com.sctvcloud.qingchuan.beans.FUsers;
import com.sctvcloud.qingchuan.beans.SingleResult;
import com.sctvcloud.qingchuan.beans.TopicContent;
import com.sctvcloud.qingchuan.beans.TopicListItem;
import com.sctvcloud.qingchuan.beans.TopicVo;
import com.sctvcloud.qingchuan.http.AbsListNetCallback;
import com.sctvcloud.qingchuan.http.AbsNetCallBack;
import com.sctvcloud.qingchuan.http.NetUtils;
import com.sctvcloud.qingchuan.http.ParamsEditor;
import com.sctvcloud.qingchuan.ui.adapter.ApplyAdapter;
import com.sctvcloud.qingchuan.ui.adapter.MyDeclareAdapter;
import com.sctvcloud.qingchuan.ui.adapter.holder.ApplyHolder;
import com.sctvcloud.qingchuan.ui.adapter.holder.TopicHolder;
import com.sctvcloud.qingchuan.ui.dialog.PicChoiceDiaFragment;
import com.sctvcloud.qingchuan.ui.dialog.ShotChoiceDiaFragment;
import com.sctvcloud.qingchuan.ui.fragment.ApplyFragment;
import com.sctvcloud.qingchuan.ui.util.IListShowData;
import com.sctvcloud.qingchuan.ui.utils.GSFPlayerScreenControllImp;
import com.sctvcloud.qingchuan.ui.utils.PictureUtils;
import com.sctvcloud.qingchuan.ui.utils.SkipUtil;
import com.sctvcloud.qingchuan.ui.utils.TitleUtils;
import com.sctvcloud.qingchuan.utils.UserManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.common.util.LogUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 我的申报
 */
public class MyDeclareActivity extends BaseActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener
        , CanRefreshLayout.IScrollView {
    @BindView(R.id.rebllion_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected CustomLinearLayout detail;
    @BindView(R.id.rebllion_list)
    protected RecyclerView rebllion_list;
    @BindView(R.id.video_container)
    protected AbsoluteLayout videoContainer;
    @BindView(R.id.my_content_no)
    protected LinearLayout contentnoLayout;
    @BindView(R.id.title_top_share)
    protected CustomFontTextView publish;

    private MyDeclareAdapter mAdapter;
    private boolean mIsLoading = false;
    private int mPageNo = 0;
    private int mPageAll = 0;
    private int tag_mPageNo = 0;
    private int tag_mPageAll = 0;
    private final static int pageSize = 10;
    private PicChoiceDiaFragment picChoiceDiaFragment;
    private ShotChoiceDiaFragment shotChoiceDiaFragment;
    public static final String PIC_TAG = "dia_pic_choice_fragment";
    public static final String SHOT_TAG = "dia_shot_choice_fragment";
    private int themeId;
    private List<LocalMedia> selectList = new ArrayList<>();
    public static final String EX_TYPE = "ex_type";
    private int type = -1;//-1代表直接跳转爆料提交,1代表选择图片后提交爆料
    private Handler mHandler;
    private GSFPlayerScreenControllImp screenController;
    protected static final int CODE_REQUEST_LOGIN = 303;
    private RecyclerView.OnScrollListener scrollListener;

    private LayoutInflater mInflater;

    private List<IListShowData> dataList = new ArrayList<>();
    private boolean my = false;
    private boolean is_mine = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this).useAndSetTxTitle("我的申报");
        themeId = R.style.picture_default_style;
        mHandler = new Handler();
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_my_declare);
        ButterKnife.bind(this);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    private void initView() {
        publish.setText("立即申报");
        publish.setTextColor(getResources().getColor(R.color.colorHomeText));
        publish.setBackground(null);
        publish.setVisibility(View.VISIBLE);
        final int pa = getResources().getDimensionPixelOffset(R.dimen.divider_shadow_margin_bottom);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        rebllion_list.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        rebllion_list.setItemAnimator(new DefaultItemAnimator());
//        rebllion_list.addItemDecoration(new RBaseItemDecoration(2));
        detail.setiScrollView(this);
        refreshLayout.autoRefresh();
        mInflater = LayoutInflater.from(this);


    }


    @Override
    public void onLoadMore() {
        getData();
    }


    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        mPageNo = 0;
        tag_mPageNo = 0;
        mIsLoading = true;
        dataList.clear();
        getData();
    }
    DeclareVo dVo;
    private void getData() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("page", mPageNo);
        param.put("size", pageSize);
        FUsers user = UserManager.getInstance().getUser();
        if (user != null && !TextUtils.isEmpty(user.getUserId())) {
            param.put("userId", user.getUserId());
        }

        NetUtils.getNetAdapter().getMyDeclare(getOwnerName(), user.getUserId(), mPageNo, pageSize, new AbsNetCallBack<DeclareVo>(DeclareVo.class) {
            @Override
            public void onSuc(DeclareVo vo) {
                if (null != vo) {
                    dVo = vo;
                    if (!ListUtils.isListValued(vo.getContent())) {
                        initData(null);
                        return;
                    }

                    if (mPageAll == 0) {
                        mPageAll = vo.getTotalPages();
                    }
                    initData(vo.getContent());
                } else {
                    initData(null);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast(R.string.loading_no_data);
                initData(null);
            }

            @Override
            public void onEnd() {
                onNetFinish();
            }
        });
    }

    private void initData(List<DeclareBean> DeclareBeans) {
        if (DeclareBeans == null || DeclareBeans.size() == 0) {
            DeclareBeans = new ArrayList<>();
        }
//        if (ListUtils.isListValued(DeclareBeans)){
//            DeclareBeans.get(0).getDiscloseImage().get(0).setImageUrl("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1507787519984&di=5ac3e6dcde804a18ac62ff69f562d7ff&imgtype=0&src=http%3A%2F%2Fa.hiphotos.baidu.com%2Fzhidao%2Fpic%2Fitem%2F0823dd54564e9258b9b28bca9882d158ccbf4e0b.jpg");
//        }
        dataList.addAll(DeclareBeans);
        if (0 < dataList.size()) {
            refreshLayout.setVisibility(View.VISIBLE);
            contentnoLayout.setVisibility(View.GONE);
        } else {
            refreshLayout.setVisibility(View.GONE);
            contentnoLayout.setVisibility(View.VISIBLE);
        }
        if (mAdapter == null) {
            mAdapter = new MyDeclareAdapter(this, dataList).setItemInternalClick(itemClick);
            //    mAdapter.setCommentClick(commentClick);
            rebllion_list.setAdapter(mAdapter);
            if (my) {
                mAdapter.setMy(my);
            }
        }

        if (mPageNo == 0) {
            mAdapter.setData(dataList);
        } else if (ListUtils.isListValued(DeclareBeans)) {
            List<IListShowData> list = new ArrayList<>();
            list.addAll(DeclareBeans);
            mAdapter.addDatas(list);
        }
        mPageNo++;
    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        refreshLayout.refreshComplete();
        refreshLayout.loadMoreComplete();
        if(null!=dVo) {
            refreshLayout.setLoadMoreEnabled(!dVo.isLast());
        }else{
            refreshLayout.setLoadMoreEnabled(false);
        }
    }

//

    OnItemInternalClick itemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            switch (view.getId()) {
                case R.id.item_declare_video_play:
                    itemPlayClick(itemView, view, position);
                    break;
            }
        }
    };

    private void itemPlayClick(View itemView, View view, int position) {
        if (mAdapter.getItem(position) instanceof DeclareBean) {
            DeclareBean declareBean = (DeclareBean) mAdapter.getItem(position);
            if (declareBean != null) {
                SkipUtil.skipToVideoPlayWithCover(this, UrlUtils.linkUrls(Constances.ST_BASE_URL, declareBean.getVideoUrl())
                        , declareBean.getPlayedPos(), position, declareBean.getCoverImage());
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if (resultCode == RESULT_OK) {
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                selectList = PictureSelector.obtainMultipleResult(data);
                if (ListUtils.isListValued(selectList)) {
                    Intent intent = new Intent(MyDeclareActivity.this, MyDeclareCommitActivity.class);
                    type = 1;
                    intent.putExtra(EX_TYPE, type);
                    intent.putExtra(EX_DATA, (Serializable) selectList);
                    startActivity(intent);
                }
                break;
            case SkipUtil.REQUEST_CODE_PLAY_BASE:
                playResult(resultCode, data);
                break;
        }
        // }
    }

    @Override
    public boolean canScrollUp(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(rebllion_list, -1);
    }

    @Override
    public boolean canScrollDown(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(rebllion_list, 1);
    }

    private void playResult(int resultCode, Intent intent) {
        if (intent == null || refreshLayout.isRefreshing()) {
            return;
        }
        int itemPos = intent.getIntExtra(SkipUtil.EX_POS_ITEM, -1);
        if (itemPos >= 0 && mAdapter != null) {
            if (mAdapter.getItem(itemPos) instanceof DeclareBean) {
                DeclareBean fr = (DeclareBean) mAdapter.getItem(itemPos);
                if (fr != null) {
                    if (resultCode == RESULT_OK) {
                        fr.setPlayedPos(0);
                    } else {
                        int pos = intent.getIntExtra(SkipUtil.EX_POS, -1);
                        if (pos > 0) {
                            fr.setPlayedPos(pos);
                        }
                    }
                }
            }
        }
    }

    @OnClick({R.id.title_top_share})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_top_share:
                if (!UserManager.isLoginS()) {
                    toLogin();
                    return;
                }
                Intent intent = new Intent(MyDeclareActivity.this, MyDeclareCommitActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }


}
